package com.ustarlink.pictureviewer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    int mCurrentDrawable = 0;
    int drawbleIDs[] = {
            R.drawable.p1,
            R.drawable.p2,
            R.drawable.p3,
            R.drawable.p4,
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // this app works by having two views, which get faded in/out for the cross-fade effect
        final ImageView prevImageView = (ImageView) findViewById(R.id.prevImageView);
        final ImageView nextImageView = (ImageView) findViewById(R.id.nextImageView);
        prevImageView.setBackgroundColor(Color.TRANSPARENT);
        nextImageView.setBackgroundColor(Color.TRANSPARENT);

        // Setup default ViewPropertyAnimator duration for the two imageViews
        prevImageView.animate().setDuration(1000);
        nextImageView.animate().setDuration(1000);

        // Note that a real app would do this more robustly, and not just load all possible
        // bitmaps at onCreate() time.
        final BitmapDrawable drawables[] = new BitmapDrawable[drawbleIDs.length];
        for (int i = 0; i < drawables.length; i++){
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), drawbleIDs[i]);
            drawables[i] = new BitmapDrawable(getResources(), bitmap);
        }
        prevImageView.setImageDrawable(drawables[0]);
        nextImageView.setImageDrawable(drawables[1]);

        prevImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                prevImageView.animate().alpha(0).withLayer();
                nextImageView.animate().alpha(1).withLayer().
                        withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        mCurrentDrawable = (mCurrentDrawable + 1) % drawables.length;
                        int nextDrawableIndex = (mCurrentDrawable + 1) % drawables.length;
                        prevImageView.setImageDrawable(drawables[mCurrentDrawable]);
                        nextImageView.setImageDrawable(drawables[nextDrawableIndex]);
                        nextImageView.setAlpha(0f);
                        prevImageView.setAlpha(1f);
                    }
                });
            }
        });

    }
}
